<template>
  <div class="router-view-wrapper menu-management-wrapper" @mouseup="handleOnwrapperClick">
    <div>
      <el-scrollbar class="menu-tree-wrapper">
        <el-tree ref="treeRef" :data="states.menuList" :props="{ children: 'children', label: 'name' }"
          @node-contextmenu="handleNodeRightClick" node-key="id" empty-text="" :default-expanded-keys="[`0`]"
          highlight-current @node-click="handleNodeClick" />
      </el-scrollbar>
      <div class="context-menu" :style="states.menuContextStyle">
        <el-menu mode="vertical" active-text-color="#000" background-color="aliceblue" text-color="#000">
          <el-menu-item index="1" @click="handleAddMenu">
            <img class="icon-button" src="/image/icon13.png" alt="" />
            <span>{{ lang.ADD_MENU }}</span>
          </el-menu-item>
          <el-menu-item index="2" @click="handleDeleteMenu">
            <img class="icon-button" src="/image/icon14.png" alt="" />
            <span>{{ lang.DELETE_MENU }}</span>
          </el-menu-item>
        </el-menu>
      </div>
    </div>
    <div class="menu-info-wrapper">
      <div class="button-bar-wrapper">
        <el-button type="primary" @click="handleAddColumn" :disabled="states.menuInfo.id === `0`">
          {{ lang.ADD_COLUMN }}
        </el-button>
        <el-button type="primary" @click="handleClearColumn" :disabled="states.menuInfo.id === `0`">
          {{ lang.CLEAR_COLUMN }}
        </el-button>
        <el-button type="primary" @click="handelSave" :disabled="states.menuInfo.id === `0`">
          {{ lang.SAVE }}
        </el-button>
      </div>
      <div class="main-wrapper">
        <el-form ref="formRef" :model="states.menuInfo" :rules="states.rules">
          <el-row class="form-row">
            <el-col :span="12">
              <el-row>
                <el-col :span="6" :offset="1" class="form-item-label">{{ lang.NAME_CN }} :</el-col>
                <el-col :span="12" :offset="1">
                  <el-form-item prop="nameCN">
                    <el-input v-model="states.menuInfo.nameCN" :disabled="states.menuInfo.id === `0`" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-col :span="6" :offset="1" class="form-item-label">{{ lang.NAME_EN }} :</el-col>
                <el-col :span="12" :offset="1">
                  <el-form-item prop="nameEN">
                    <el-input v-model="states.menuInfo.nameEN" :disabled="states.menuInfo.id === `0`" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>

          <el-row class="form-row">
            <el-col :span="12">
              <el-row>
                <el-col :span="6" :offset="1" class="form-item-label">{{ lang.ICON }} :</el-col>
                <el-col :span="12" :offset="1">
                  <el-form-item prop="icon">
                    <el-autocomplete v-model="states.menuInfo.icon" clearable :fetch-suggestions="getIconList"
                      :disabled="states.menuInfo.id === `0`" />
                  </el-form-item>
                </el-col>
                <el-col :span="3">
                  <img class="icon-sample" :src="`/image/${states.menuInfo.icon.split('-')[0] || 'icon2.png'}`"
                    alt="图标" />
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-col :span="6" :offset="1" class="form-item-label">{{ lang.SORT_NUMBER }} :</el-col>
                <el-col :span="12" :offset="1">
                  <el-form-item prop="sortNumber">
                    <el-input-number v-model="states.menuInfo.sortNumber" :disabled="states.menuInfo.id === `0`" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>

          <el-row class="form-row">
            <el-col :span="12">
              <el-row>
                <el-col :span="6" :offset="1" class="form-item-label">{{ lang.TYPE_CODE }} :</el-col>
                <el-col :span="12" :offset="1">
                  <el-form-item prop="typeCode">
                    <el-select v-model="states.menuInfo.typeCode" :placeholder="lang.TYPE_CODE" size="large"
                      :disabled="states.menuInfo.id === `0`" :fetch-suggestions="menuTypeList">
                      <el-option v-for="item in menuTypeList" :key='item.value' :label=item.label :value=item.value />
                      <!-- <el-option key="MenuType_AddButton" label="添加按钮" value="MenuType_AddButton" />
                      <el-option key="MenuType_EditButton" label="修改按钮" value="MenuType_EditButton" />
                      <el-option key="MenuType_BatchEditButton" label="批量修改" value="MenuType_BatchEditButton" />
                      <el-option key="MenuType_ViewButton" label="查看按钮" value="MenuType_ViewButton" />
                      <el-option key="MenuType_ExportButton" label="导出按钮" value="MenuType_ExportButton" />
                      <el-option key="MenuType_OperationButton" label="操作按钮" value="MenuType_OperationButton" /> -->
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-col :span="6" :offset="1" class="form-item-label">{{ lang.MENU_POSITION_TYPE }} :</el-col>
                <el-col :span="12" :offset="1">
                  <el-form-item prop="menuPositionCode">
                    <el-select v-model="states.menuInfo.menuPositionCode" :placeholder="lang.MENU_POSITION_TYPE"
                      size="large" :disabled="states.menuInfo.id === `0`">
                      <el-option v-for="item in menuPositionList" :key="item.value" :label="item.label"
                        :value="item.value" />
                      <!-- <el-option key="MenuPosition_ButtonBar" label="按钮行" value="MenuPosition_ButtonBar" />
                      <el-option key="MenuPosition_Row" label="记录行" value="MenuPosition_Row" />
                      <el-option key="MenuPosition_RightCick" label="右键菜单" value="MenuPosition_RightCick" />
                      <el-option key="MenuPosition_DoubleCick" label="鼠标双击" value="MenuPosition_DoubleCick" /> -->
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>

          <el-row class="form-row">
            <el-col :span="12">
              <el-row>
                <el-col :span="6" :offset="1" class="form-item-label">{{ lang.SQL }} :</el-col>
                <el-col :span="12" :offset="1">
                  <el-form-item prop="sql">
                    <el-input v-model="states.menuInfo.sql" type="textarea" resize="none"
                      :disabled="states.menuInfo.id === `0`" />
                  </el-form-item>
                </el-col>
                <el-col :span="1"
                  :style="{ display: `${states.menuInfo.typeCode === `MenuType_Menu` || states.menuInfo.typeCode === `MenuType_ViewButton` ? `block` : `none`}` }">
                  <el-tooltip class="box-item" effect="dark" :content="lang.GENERATE_COLUMNS" placement="top">
                    <img class="icon-button" src="/image/icon16.png" alt="图标" @click="handleGenerateColumns" />
                  </el-tooltip>
                </el-col>
                <el-col :span="1"
                  :style="{ display: `${states.menuInfo.typeCode === `MenuType_Menu` || states.menuInfo.typeCode === `MenuType_ViewButton` ? `none` : `block`}` }">
                  <el-tooltip class="box-item" effect="dark" :content="lang.COPY_COLUMNS" placement="top">
                    <img class="icon-button" src="/image/icon4.png" alt="图标" @click="handleCopyColumns" />
                  </el-tooltip>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-col :span="6" :offset="1" class="form-item-label">{{ lang.URL }} :</el-col>
                <el-col :span="12" :offset="1">
                  <el-form-item prop="url">
                    <el-autocomplete v-model="states.menuInfo.url" clearable :fetch-suggestions="getUrlList"
                      :disabled="states.menuInfo.id === `0`">
                      <template #default="{ item }">
                        <span>{{ item.name }}</span>
                      </template>
                    </el-autocomplete>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-form>

        <div class="table-wrapper">
          <el-table :data="states.menuInfo.columnList" :stripe="true" :border="true" style="width: 100%;" height="100%">
            <el-table-column fixed="left" :label="lang.OPERATION" width="200">
              <template #default="scope">
                <el-button link type="primary" size="small" @click.prevent="handleEditColumn(scope.$index)">
                  {{ lang.EDIT }}
                </el-button>
                <el-button link type="primary" size="small" @click.prevent="handleDeleteColumn(scope.$index)">
                  {{ lang.DELETE }}
                </el-button>
                <el-button link type="primary" size="small" @click.prevent="handleMoveUpColumn(scope.$index)">
                  {{ lang.MOVE_UP }}
                </el-button>
                <el-button link type="primary" size="small" @click.prevent="handleMoveDownColumn(scope.$index)">
                  {{ lang.MOVE_DOWN }}
                </el-button>
              </template>
            </el-table-column>
            <el-table-column prop="field" :label="lang.FIELD" />
            <el-table-column prop="nameCN" :label="lang.NAME_CN" />
            <el-table-column prop="nameEN" :label="lang.NAME_EN" />
            <el-table-column prop="width" :label="lang.WIDTH" />
            <el-table-column prop="isReadonly" :label="lang.IS_READONLY">
              <template #default="scope">
                <el-tag v-if="scope.row.isReadonly" type="success">{{ lang.YES }}</el-tag>
                <el-tag v-else type="danger">{{ lang.NO }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="isHidden" :label="lang.IS_HIDDEN">
              <template #default="scope">
                <el-tag v-if="scope.row.isHidden" type="success">{{ lang.YES }}</el-tag>
                <el-tag v-else type="danger">{{ lang.NO }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="isSearchable" :label="lang.IS_SEARCHABLE">
              <template #default="scope">
                <el-tag v-if="scope.row.isSearchable" type="success">{{ lang.YES }}</el-tag>
                <el-tag v-else type="danger">{{ lang.NO }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="controlTypeCode" :label="lang.CONTROLE_TYPE_CODE">
              <template #default="scope">
                {{ states.controlTypeCode[scope.row.controlTypeCode] }}
              </template>
            </el-table-column>
            <el-table-column prop="dataSource" :label="lang.DATA_SOURCE">
              <template #default="scope">
                <el-popover v-if="scope.row.dataSource?.length > 20" effect="light" trigger="hover" placement="top"
                  width="auto">
                  <template #default>
                    <span>{{ scope.row.dataSource }}</span>
                  </template>
                  <template #reference>
                    <span>{{ scope.row.dataSource?.substring(0, 20) }}</span>
                  </template>
                </el-popover>
                <span v-else>{{ scope.row.dataSource }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <el-dialog v-model="states.columnDialog.visible" :title="states.columnDialog.title" top="5vh"
      @closed="handleOnColumnDialogClose">
      <el-form :model="states.columnDialog.value" ref="columnFormRef" :rules="states.columnDialog.rules"
        :close-on-click-modal="false" :close-on-press-escape="false">
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item :label="lang.FIELD" prop="field" :labelWidth="120">
              <el-input v-model="states.columnDialog.value.field" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item :label="lang.NAME_CN" prop="nameCN" :labelWidth="120">
              <el-input v-model="states.columnDialog.value.nameCN" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item :label="lang.NAME_EN" prop="nameEN" :labelWidth="120">
              <el-input v-model="states.columnDialog.value.nameEN" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item :label="lang.WIDTH" prop="width" :labelWidth="120">
              <el-input v-model="states.columnDialog.value.width" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item :label="lang.IS_READONLY" prop="isReadonly" :labelWidth="120">
              <el-switch v-model="states.columnDialog.value.isReadonly" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item :label="lang.IS_HIDDEN" prop="isHidden" :labelWidth="120">
              <el-switch v-model="states.columnDialog.value.isHidden" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item :label="lang.IS_SEARCHABLE" prop="isSearchable" :labelWidth="120">
              <el-switch v-model="states.columnDialog.value.isSearchable" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item :label="lang.CONTROLE_TYPE_CODE" prop="controlTypeCode" :labelWidth="120">
              <el-select v-model="states.columnDialog.value.controlTypeCode">
                <el-option v-for="(value, key, index) in states.controlTypeCode" :key="key" :label="value"
                  :value="key" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item :label="lang.DATA_SOURCE" prop="dataSource" :labelWidth="120">
              <el-autocomplete v-model="states.columnDialog.value.dataSource" clearable style="width:100%;"
                ref="dataSourceInputRef" :fetch-suggestions="getDictionaryList">
                <template #default="{ item }">
                  <span>{{ item.name }}</span>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>
        <el-table :data="states.columnDialog.value.rules" :stripe="true" :border="true"
          style="width: 80%;margin-left: 10%;" height="200">
          <el-table-column fixed="left" :label="lang.OPERATION" width="120">
            <template #default="scope">
              <el-button link type="primary" size="small" @click.prevent="handelEditRule(scope.$index)">
                {{ lang.EDIT }}
              </el-button>
              <el-button link type="primary" size="small" @click.prevent="handleDeleteRule(scope.$index)">
                {{ lang.DELETE }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column prop="regExp" :label="lang.REG_EXP" />
          <el-table-column prop="message" :label="lang.MESSAGE" />
        </el-table>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="handleAddRule">{{ lang.ADD_RULE }}</el-button>
          <el-button @click="handleColumnDialogCancel">{{ lang.CANCEL }}</el-button>
          <el-button type="primary" @click="handleColumnDialogConfirm">{{ lang.CONFIRM }}</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="states.ruleDialog.visible" :title="states.ruleDialog.title" @closed="handleOnRuleDialogClose"
      :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="states.ruleDialog.value" ref="ruleFormRef" :rules="states.ruleDialog.rules">
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item :label="lang.REG_EXP" prop="regExp" :labelWidth="120">
              <el-autocomplete v-model="states.ruleDialog.value.regExp" clearable :fetch-suggestions="getRuleList">
                <template #default="{ item }">
                  <span>{{ item.name }}</span>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item :label="lang.MESSAGE" prop="message" :labelWidth="120">
              <el-input v-model="states.ruleDialog.value.message" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="handelRuleDialogCancel">{{ lang.CANCEL }}</el-button>
          <el-button type="primary" @click="handleRuleDialogConfirm">{{ lang.CONFIRM }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue';
import { lang } from "../../lang";
import { ElAutocomplete } from "element-plus";

const treeRef = ref();
const formRef = ref();
const columnFormRef = ref();
const ruleFormRef = ref();

const props = defineProps([
  "request",
  "success",
  "warning",
  "info",
  "error",
  "loading",
  "confirm",
  "closeLoading",
]);

const states = reactive({
  menuList: [],
  menuContextStyle: { left: `100px`, top: `100px`, display: `none` },
  tableHeight: "100%",
  dictionary: [],
  menuInfo: {
    id: "0",
    nameCN: "顶级菜单",
    nameEN: "Top Menu",
    icon: "home.png",
    sortNumber: 0,
    typeCode: "MenuType_Menu",
    menuPositionCode: "MenuPosition_Menu",
    url: "",
    sql: "",
    columnList: [],
  },
  rules: {
    nameCN: [{ required: true, message: `${lang.PLEASE_INPUT}${lang.NAME_CN}` }],
    nameEN: [{ required: true, message: `${lang.PLEASE_INPUT}${lang.NAME_EN}` }],
    icon: [{ required: true, message: `${lang.PLEASE_INPUT}${lang.ICON}` }],
    sortNumber: [{ required: true, message: `${lang.PLEASE_INPUT}${lang.SORT_NUMBER}` }],
    typeCode: [{ required: true, message: `${lang.PLEASE_INPUT}${lang.TYPE_CODE}` }],
    menuPositionCode: [{ required: true, message: `${lang.PLEASE_INPUT}${lang.MENU_POSITION_TYPE}` }],
  },
  columnDialog: {
    visible: false,
    title: "",
    value: {
      index: undefined,
      field: "",
      nameCN: "",
      nameEN: "",
      width: "",
      isReadonly: false,
      isHidden: false,
      isSearchable: false,
      controlTypeCode: "",
      dataSource: "",
      rules: []
    },
    rules: {
      field: [{ required: true, message: `${lang.PLEASE_INPUT}${lang.FIELD}` }],
      nameCN: [{ required: true, message: `${lang.PLEASE_INPUT}${lang.NAME_CN}` }],
      nameEN: [{ required: true, message: `${lang.PLEASE_INPUT}${lang.NAME_EN}` }],
      isReadonly: [{ required: true, message: `${lang.PLEASE_INPUT}${lang.IS_READONLY}` }],
      isHidden: [{ required: true, message: `${lang.PLEASE_INPUT}${lang.IS_HIDDEN}` }],
      isSearchable: [{ required: true, message: `${lang.PLEASE_INPUT}${lang.IS_SEARCHABLE}` }],
      controlTypeCode: [{ required: true, message: `${lang.PLEASE_INPUT}${lang.CONTROLE_TYPE_CODE}` }],
    }
  },
  ruleDialog: {
    visible: false,
    title: "",
    value: {
      index: undefined,
      regExp: "",
      message: ""
    },
    rules: {
      regExp: [{ required: true, message: `${lang.PLEASE_INPUT}${lang.REG_EXP}` }],
      message: [{ required: true, message: `${lang.PLEASE_INPUT}${lang.MESSAGE}` }],
    }
  },
  controlTypeCode: {
    "ControlType_String": "文本",
    "ControlType_Number": "数值",
    "ControlType_Boolean": "布尔值",
    "ControlType_Date": "日期",
    "ControlType_DateTime": "日期时间",
    "ControlType_Select": "下拉框",
    "ControlType_MultiSelect": "多选下拉框",
  }
});

const getIconList = async (queryString, callback) => {
  callback([
    // { value: "icon1.png-设置" },
    // { value: "icon2.png-作业" },
    // { value: "icon3.png" },
    // { value: "icon4.png" },
    // { value: "icon5.png" },
    // { value: "icon6.png" },
    // { value: "icon7.png" },
    // { value: "icon8.png" },
    // { value: "icon9.png" },
    // { value: "icon10.png" },
    // { value: "icon11.png" },
    // { value: "icon12.png" },
    { value: "icon13.png-新增" },
    { value: "icon14.png-删除" },
    { value: "icon15.png-编辑" },
    { value: "icon16.png-刷新" },
    { value: "icon17.png-查看" },
    { value: "icon18.png-选中" },
    // { value: "icon19.png" }
  ]);
};

const getUrlList = async (queryString, callback) => {
  callback([
    { value: "/MenuManagement", name: "菜单管理" },
    { value: "/RoleManagement", name: "角色管理" },
    { value: "/UserManagement", name: "用户管理" },
    { value: "/SystemDataPage", name: "系统数据展示页" },
    { value: "System/AddData", name: "系统接口-新增数据" },
    { value: "System/EditData", name: "系统接口-编辑数据" },
    { value: "System/BatchEditData", name: "系统接口-批量编辑" },
    { value: "System/ViewData", name: "系统接口-查看数据" },
    { value: "System/ExportData", name: "系统接口-导出数据" },
    { value: "System/OperateData", name: "系统接口-操作数据" },
  ])
};

const getRuleList = async (queryString, callback) => {
  callback([
    { value: "required", name: "必填" },
    { value: "Max:1", name: "字符串:最大长度,数值:最大值" },
    { value: "Min:1", name: "字符串:最小长度,数值:最小值" },
    { value: "Len:1", name: "限制固定长度" },
  ])
};

const menuTypeList = [
  { value: "MenuType_Menu", label: "菜单" },
  { value: "MenuType_AddButton", label: "添加按钮" },
  { value: "MenuType_EditButton", label: "修改按钮" },
  { value: "MenuType_BatchEditButton", label: "批量修改" },
  { value: "MenuType_ViewButton", label: "查看按钮" },
  { value: "MenuType_ExportButton", label: "导出按钮" },
  { value: "MenuType_OperationButton", label: "操作按钮" }
];

const menuPositionList = [
  { value: "MenuPosition_Menu", label: "菜单" },
  { value: "MenuPosition_ButtonBar", label: "按钮行" },
  { value: "MenuPosition_Row", label: "记录行" },
  { value: "MenuPosition_RightCick", label: "右键菜单" },
  { value: "MenuPosition_DoubleCick", label: "鼠标双击" }
];

const getDictionaryList = async (callback) => {
  callback([
    { value: "required", name: "必填" },
    { value: "Max:1", name: "字符串:最大长度,数值:最大值" },
    { value: "Min:1", name: "字符串:最小长度,数值:最小值" },
    { value: "Len:1", name: "限制固定长度" },
  ])
};

const showContextMenu = async (x, y) => {
  states.menuContextStyle = { left: `${x}px`, top: `${y}px`, display: `block` };
};

const hideContextMenu = async () => {
  states.menuContextStyle = { left: `0px`, top: `0px`, display: `none` };
};

const showColumnDialog = async () => {
  states.columnDialog.visible = true;
};

const hideColumnDialog = async () => {
  states.columnDialog.visible = false;
};

const showRuleDialog = async () => {
  states.ruleDialog.visible = true;
};

const hideRuleDialog = async () => {
  states.ruleDialog.visible = false;
};

const getMenuList = async () => {
  let response = await props.request("Menu/GetAllMenuList", {});
  if (response.Code === "S") {
    states.menuList = response.Data;
  } else {
    props.error(response.Msg);
  }
};

const getMenuConfig = async () => {
  let currentKey = treeRef.value.getCurrentKey();
  if (currentKey !== states.menuInfo.id) {
    let response = await props.request("Menu/GetMenuConfig", { menuId: currentKey });
    if (response.Code === "S") {
      states.menuInfo = response.Data;
    } else {
      props.error(response.Msg);
    }
  }
};

const getDictionary = async () => {
  let response = await props.request("System/GetDictionaryType", {});
  if (response.Code === "S") {
    states.dictionary = [
      ...response.Data.dictionary["0"].map(item => { return { value: `DIC:${item.id}`, name: item.text }; }),
      { value: `SELECT <值字段> AS ID,<文本字段> AS TEXT FROM <表名>`, name: "查询语句" },
      { value: `SELECT <值字段> AS ID,<文本字段> AS TEXT,'<绑定字段>:' || <绑定字段> AS BIND FROM <表名>;<绑定字段>`, name: "绑定联动" },
      { value: `SELECT <值字段> AS ID,<文本字段> AS TEXT,'<绑定字段1>:' || <绑定字段1> || '<绑定字段2>:' || <绑定字段2> AS BIND FROM <表名>;<绑定字段1>,<绑定字段2>`, name: "绑定多字段联动" }
    ];
  } else {
    props.error(response.Msg);
  }
};

const handleOnwrapperClick = async (e) => {
  hideContextMenu();
};

const handleNodeRightClick = async (e, data, node) => {
  treeRef.value.setCurrentKey(data.id);
  getMenuConfig();
  showContextMenu(e.pageX, e.pageY);
};

const handleNodeClick = async (e) => {
  hideContextMenu();
  getMenuConfig();
};

const handleAddMenu = async () => {
  let currentKey = treeRef.value.getCurrentKey();
  let response = await props.request("Menu/AddMenu", { parentId: currentKey });
  if (response.Code === "S") {
    await getMenuList();
    treeRef.value.setCurrentKey(response.Data);
  } else {
    props.error(response.Msg);
  }
};

const handleDeleteMenu = async () => {
  let currentKey = treeRef.value.getCurrentKey();
  let response = await props.request("Menu/DeleteMenu", { menuId: currentKey });
  if (response.Code === "S") {
    await getMenuList();
    treeRef.value.setCurrentKey(response.Data);
  } else {
    props.error(response.Msg);
  }
};

const handleAddColumn = async () => {
  states.columnDialog.title = lang.ADD_COLUMN;
  showColumnDialog();
};

const handleClearColumn = async () => {
  states.menuInfo.columnList = [];
};

const handleEditColumn = async (index) => {
  states.columnDialog.title = lang.EDIT_COLUMN;
  states.columnDialog.value = { ...states.menuInfo.columnList[index], index: index };
  showColumnDialog();
};

const handleDeleteColumn = async (index) => {
  states.menuInfo.columnList = states.menuInfo.columnList.filter((item, rowIndex) => rowIndex !== index);
};

const handleMoveUpColumn = async (index) => {
  if (index > 0) {
    let tempColumn = states.menuInfo.columnList[index - 1];
    states.menuInfo.columnList[index - 1] = states.menuInfo.columnList[index];
    states.menuInfo.columnList[index] = tempColumn;
  }
};

const handleMoveDownColumn = async (index) => {
  if (index < states.menuInfo.columnList.length - 1) {
    let tempColumn = states.menuInfo.columnList[index + 1];
    states.menuInfo.columnList[index + 1] = states.menuInfo.columnList[index];
    states.menuInfo.columnList[index] = tempColumn;
  }
};

const handleAddRule = async () => {
  states.ruleDialog.title = lang.ADD_RULE;
  showRuleDialog();
};

const handelEditRule = async (index) => {
  states.ruleDialog.title = lang.EDIT_RULE;
  states.ruleDialog.value = { ...states.columnDialog.value.rules[index], index: index };
  showRuleDialog();
};

const handleDeleteRule = async (index) => {
  states.columnDialog.value.rules = states.columnDialog.value.rules.filter((item, rowIndex) => rowIndex !== index);
};

const handleColumnDialogCancel = async () => {
  hideColumnDialog();
};

const handleColumnDialogConfirm = async () => {
  let checked = false;
  try {
    checked = await columnFormRef.value.validate();
  }
  catch { }
  if (checked) {
    if (states.columnDialog.value.index === undefined) {
      states.menuInfo.columnList.push({ ...states.columnDialog.value, index: undefined });
    } else {
      states.menuInfo.columnList[states.columnDialog.value.index] = { ...states.columnDialog.value, index: undefined };
    }
    hideColumnDialog();
  }
};

const handleOnColumnDialogClose = async () => {
  states.columnDialog.value = {
    index: undefined,
    field: "",
    nameCN: "",
    nameEN: "",
    width: "",
    isReadonly: false,
    isHidden: false,
    isSearchable: false,
    controlTypeCode: "",
    dataSource: "",
    rules: []
  }
};

const handelRuleDialogCancel = async () => {
  hideRuleDialog();
};

const handleRuleDialogConfirm = async () => {
  let checked = false;
  try {
    checked = await ruleFormRef.value.validate();
  }
  catch { }
  if (checked) {
    if (states.ruleDialog.value.index === undefined) {
      states.columnDialog.value.rules.push({ ...states.ruleDialog.value, index: undefined });
    } else {
      states.columnDialog.value.rules[states.ruleDialog.value.index] = { ...states.ruleDialog.value, index: undefined };
    }
    hideRuleDialog();
  }
};

const handleOnRuleDialogClose = async () => {
  states.ruleDialog.value = {
    index: undefined,
    regExp: "",
    message: ""
  }
};

const handelSave = async () => {
  let checked = false;
  try {
    checked = await formRef.value.validate();
  }
  catch { }

  if (checked) {
    let response = await props.request("Menu/EditMenu", states.menuInfo);
    if (response.Code === "S") {
      props.success(response.Msg);
      await getMenuList();
      treeRef.value.setCurrentKey(states.menuInfo.id);
    } else {
      props.error(response.Msg);
    }
  }
};

const handleGenerateColumns = async () => {
  let response = await props.request("Menu/GenerateColumns", { sql: states.menuInfo.sql });
  if (response.Code === "S") {
    states.menuInfo.columnList = response.Data.map(column => {
      let index = states.menuInfo.columnList.findIndex(oldColumn => oldColumn.field === column.field);
      if (index < 0) return column;
      else return states.menuInfo.columnList[index];
    });
  } else {
    props.error(response.Msg);
  }
};

const handleCopyColumns = async () => {
  if (states.menuInfo.typeCode === "MenuType_AddButton"
    || states.menuInfo.typeCode === "MenuType_EditButton"
    || states.menuInfo.typeCode === "MenuType_BatchEditButton") {
    let currentKey = treeRef.value.getCurrentKey();
    let response = await props.request("Menu/CopyColumns", { menuId: currentKey });
    if (response.Code === "S") {
      states.menuInfo.columnList = response.Data.map(column => {
        let index = states.menuInfo.columnList.findIndex(oldColumn => oldColumn.field === column.field);
        if (index < 0) return column;
        else return states.menuInfo.columnList[index];
      });

      if (states.menuInfo.sql === "") {
        if (states.menuInfo.typeCode === "MenuType_AddButton") {
          states.menuInfo.sql = `INSERT INTO <替换表名> ("ID",${states.menuInfo.columnList.filter(column => !column.isHidden).map(column => `"${column.field.toUpperCase()}"`).join(",")},"WAREHOUSE_CODE","CREATE_DATE","CREATED_BY","MODIFY_IP","IS_DELETED")`
            + `VALUES (:ID,${states.menuInfo.columnList.filter(column => !column.isHidden).map(column => `:${column.field.toUpperCase()}`).join(",")},:WAREHOUSE_CODE,:CREATE_DATE,:CREATED_BY,:MODIFY_IP,:IS_DELETED)`;
        } else {
          states.menuInfo.sql = `UPDATE <替换表名> SET "MODIFY_DATE"=:MODIFY_DATE,"MODIFIED_BY"=:MODIFIED_BY,"MODIFY_IP"=:MODIFY_IP,${states.menuInfo.columnList.filter(column => !column.isHidden).map(column => `"${column.field.toUpperCase()}"=:${column.field.toUpperCase()}`).join(",")} WHERE "ID" IN :ID`
        }
      }
    } else {
      props.error(response.Msg);
    }
  }
};

onMounted(() => {
  getMenuList();
  getDictionary();
});

</script>
<style scoped lang="less">
@import "../../index.less";
@menu-tree-width: 200px;
@button-bar-height: 60px;

.menu-management-wrapper {
  display: flex;

  .menu-tree-wrapper {
    width: calc(~"@{menu-tree-width} - 1px");
    height: calc(~"@{page-wrapper-height} - @{header-height}");
    border-right: 1px solid #f1f1f1;
  }

  .context-menu {
    position: absolute;
    z-index: 99;
    background-color: aliceblue;
  }

  .menu-info-wrapper {
    width: calc(~"@{page-wrapper-width} - @{sider-width} - @{menu-tree-width} - 20px");
    height: calc(~"@{page-wrapper-height} - @{header-height}");
    margin: 0 10px;

    .button-bar-wrapper {
      width: 100%;
      height: @button-bar-height;
      display: flex;
      justify-content: start;
      align-items: center;
    }

    .main-wrapper {
      width: 100%;
      height: calc(~"@{page-wrapper-height} - @{header-height} - @{button-bar-height}");

      .form-row {
        height: 70px;

        .form-item-label {
          display: flex;
          justify-content: end;
          align-items: top;
        }
      }

      .icon-sample {
        width: 2rem;
        height: 2rem;
      }

      .icon-button {
        width: 18px;
        height: 18px;
      }

      .icon-button:hover {
        cursor: pointer;
      }

      .table-wrapper {
        width: 100%;
        height: calc(~"@{page-wrapper-height} - @{header-height} - @{button-bar-height} - 300px");
      }
    }
  }
}
</style>
